package proxy.impl;

import handler.RestHandler;
import handler.WebRestClient;
import lombok.extern.slf4j.Slf4j;
import model.MethodInfo;
import model.ServerInfo;
import org.springframework.stereotype.Component;
import proxy.ProxyCreator;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@Slf4j
public class jdkProxyCreator implements ProxyCreator {
    @Override
    public Object createProxy(Class<?> type) {
        log.info("createProxy: " + type);
        ServerInfo serverInfo = extractServerInfo(type);
        log.info("serverInfo: " + serverInfo);
        RestHandler restHandler = new WebRestClient();
        // 初始化
        restHandler.init(serverInfo);
        Object proxyInstance = Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{type},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        MethodInfo methodInfo = extractMethodInfo(method, args);
                        log.info("methodInfo: " + methodInfo);
                        return restHandler.invoke(methodInfo);
                    }
                });
        return proxyInstance;
    }




}
